<?php
declare(strict_types=1);

namespace App\User\Controller;

use App\Common\Constants\ErrorCode;
use App\Common\Controller\AbstractController;
use App\Common\Middleware\JwtAuthMiddleware;
use App\Common\Middleware\PermissionMiddleware;
use App\User\Request\UserRequest;
use App\User\Service\PermissionService;
use App\User\Service\UserService;
use Exception;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\SimpleCache\InvalidArgumentException;

/**
 * @Controller()
 * @Middlewares({
 *     @Middleware(JwtAuthMiddleware::class),
 *     @Middleware(PermissionMiddleware::class)
 * })
 */
class UserController extends AbstractController
{

    /**
     * @Inject()
     * @var UserService
     */
    private $userService;

    /**
     * @Inject()
     * @var PermissionService
     */
    private $permissionService;

    const USER = 2;

    /**
     * 获取用户列表
     * @RequestMapping(path="/v1/user", methods="get")
     * @param RequestInterface $request
     *
     * @return array
     */
    public function index(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = isset($params['perpage']) ? (int)($params['perpage']) : 15;
        $res = $this->userService->getList($params, (int)$perPage);

        if (!$res['code']) {
            return $this->success($res['data']->items(), '获取成功', $res['data']->total());
        } else {
            return $this->failed($res['code']);
        }

    }

    /**
     * 获取指定用户信息
     * @RequestMapping(path="/v1/user/{id:\d+}", methods="get")
     * @param int $id
     *
     * @return array
     */
    public function info(int $id)
    {
        if (!$id) return $this->failed(ErrorCode::SYSTEM_INVALID);
        $res = $this->userService->getInfoById((int)$id);
        if (!$res['code']) {
            return $this->success($res['data'], '获取成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 新增后台用户
     * @PostMapping(path="/v1/user", methods="post")
     * @param UserRequest $request
     *
     * @return array
     * @throws Exception
     */
    public function store(UserRequest $request)
    {
        $params = $request->validated();
        $res = $this->userService->add($params, self::USER);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 编辑后台用户
     * @PutMapping(path="/v1/user/{id:\d+}", methods="put")
     * @param int $id
     * @param UserRequest $request
     *
     * @return array
     * @throws Exception
     */
    public function update(int $id, UserRequest $request)
    {
        $params = $request->all();
        $params['id'] = $id;
        $res = $this->userService->update($params);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 删除后台用户（软删除）
     * @DeleteMapping(path="/v1/user/{id:\d+}", methods="delete")
     * @param int $id
     *
     * @return array
     */
    public function delete(int $id)
    {
        if ($id == 1) return $this->failed(ErrorCode::ADMIN_IS_GOD);
        $res = $this->userService->delete((int)$id);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 只查询被删除用户
     * @RequestMapping(path="/v1/user/destroy", methods="get")
     * @param RequestInterface $request
     *
     * @return array
     */
    public function destoryList(RequestInterface $request)
    {
        $perPage = isset($request->perpage) ? (int)($request->perpage) : 15;
        $res = $this->userService->getDestoryList($perPage);
        if (!$res['code']) {
            return $this->success($res['data']->items(), '获取成功', $res['data']->total());
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 删除后台用户（强删除）
     * @DeleteMapping(path="/v1/user/{id:\d+}/destroy", methods="delete")
     * @param int $id
     *
     * @return array
     */
    public function destroy(int $id)
    {
        if ($id == 1) return $this->failed(ErrorCode::ADMIN_IS_GOD);
        $res = $this->userService->forceDelete($id);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 恢复被软删除的用户（可批量）
     * @PostMapping(path="/v1/user/restore", methods="post")
     * @param RequestInterface $request
     *
     * @return array
     */
    public function restore(RequestInterface $request)
    {
        $ids = $request->input('ids');
        if (!$ids) return $this->failed(ErrorCode::SYSTEM_INVALID);
        $res = $this->userService->restore($ids);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 用户启用/禁用
     * @PutMapping(path="/v1/user/{id:\d+}/status", methods="put")
     * @param int $id
     *
     * @return array
     */
    public function editStatus(int $id)
    {
        if ($id == 1) return $this->failed(ErrorCode::ADMIN_IS_GOD);
        $res = $this->userService->editStatus('user', (int)$id, '2');
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 用户退出
     * @PostMapping(path="/v1/user/logout", methods="post")
     * @return array
     * @throws InvalidArgumentException
     */
    public function logout()
    {
        if ($this->userService->logout()) {
            return $this->success('', '退出登录成功');
        }
        return $this->failed(ErrorCode::SERVER_ERROR);
    }


    /**
     * 用户添加/修改角色
     * @PostMapping(path="/v1/user/role", methods="post")
     * @param RequestInterface $request
     *
     * @return array
     */
    public function addRole(RequestInterface $request)
    {
        $userId = $request->input('user_id');
        $roleId = $request->input('role_id');
        if (!$userId || !$roleId) return $this->failed(ErrorCode::PARAMS_INVALID);
        $res = $this->permissionService->handRoleOrPermission((int)$userId, $roleId, 2);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 获取用户所有权限节点
     * @RequestMapping(path="/v1/user/permission", methods="get")
     * @param RequestInterface $request
     *
     * @return array
     */
    public function permissionList(RequestInterface $request)
    {
        $userId = $request->input('user_id') ?? 0;
        $res = $this->permissionService->permissionList((int)$userId);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }


    /**
     * 修改后台管理员用户密码
     * @RequestMapping(path="/v1/user/password", methods="put")
     * @param RequestInterface $request
     *
     * @return array
     */
    public function editPassword(RequestInterface $request)
    {
        $params = $request->all();
        if(!$params['id'] || !$params['old_password'] || !$params['new_password']){
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        $res = $this->userService->editPassword($params);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }
}
